/**
 * @作者 7七月
 * @微信公号 林间有风
 * @开源项目 $ http://7yue.pro
 * @免费专栏 $ http://course.7yue.pro
 * @我的课程 $ http://imooc.com/t/4294850
 * @创建时间 2020-01-21 15:34
 */
package com.lucas.springboot_restful_api.dto.validators;

import com.lucas.springboot_restful_api.dto.UserRegisterDTO;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PasswordValidator implements ConstraintValidator<PasswordEqual, UserRegisterDTO> {
    private int min;
    private int max;

    @Override
    public void initialize(PasswordEqual constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(UserRegisterDTO dto, ConstraintValidatorContext vc) {
        String password1 = dto.getPassword1();
        String password2 = dto.getPassword2();
        boolean isMatch = password1.equals(password2);
        if (! isMatch) {
            return false;
        }
        boolean isInLength = (min <= password1.length() && password1.length() <= max);
        if (! isInLength) {
            vc.disableDefaultConstraintViolation();;
            vc.buildConstraintViolationWithTemplate("密码长度应在" + min + "与" + max + "之间").addConstraintViolation();
            return false;
        }
        return true;

    }
}
